<script lang="ts" setup>
import { reactive, ref, watch } from "vue"
import { type IGetJobData } from "@/api/job/types/job"
import {
  type FormInstance,
  ElMessage,
  type FormRules,
  type UploadUserFile,
  type UploadProps,
  type TabsPaneContext
} from "element-plus"
import { Search, Refresh, Download } from "@element-plus/icons-vue"
import { formatDateTime } from "@/utils/index"
import { usePagination } from "@/hooks/usePagination"
import { getwithdrawList, getwithdrawUpdate, getyunuserAll, dakuanjiesuandown } from "@/api/yunShang"
import { ComplaintUpload } from "@/api/complaint"
defineOptions({
  name: "XcxYsmoneyTX"
})
const loading = ref(false)
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()
// #region 分销账号
const userNameList = ref()
const getyunuserData = () => {
  getyunuserAll().then((res: any) => {
    console.log(res, "分销账号")
    userNameList.value = res.data
  })
}
getyunuserData()

//#region 增
const dialogVisible = ref<boolean>(false)
const formRef = ref<FormInstance | null>(null)
const formData = reactive<any>({
  id: "",
  note: "",
  state: 0,
  image: ""
})
const formRules: FormRules = reactive({
  // image: [{ required: true, trigger: "change", message: "请上传图片" }],
  note: [{ required: true, trigger: "change", message: "请上传图片" }]
})
const handleCreate = () => {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      uploadFuc()
    } else {
      return false
    }
  })
}
const resetForm = () => {
  currentUpdateId.value = undefined
  clearValidate()
}
//#endregion

//#region 打款成功
const currentUpdateId = ref<undefined | string>(undefined)
const handleUpdate = (row: IGetJobData) => {
  dialogVisible.value = true
  currentUpdateId.value = row.id
  console.log(row, "数据详情")
  formData.id = row.id
}
const handleUpdate1 = (row: IGetJobData) => {
  dialogVisible.value = true
  currentUpdateId.value = undefined
  console.log(row, "数据详情")
  formData.id = row.id
}
//#endregion

//#region 查
const tableData = ref<IGetJobData[]>([])
const searchFormRef = ref<FormInstance | null>(null)
const searchData = reactive({
  userName: "", // 分销账号
  time: "" // 时间
})
const stateSP = ref<any>(0)
const getTableData = () => {
  getwithdrawList({
    page: paginationData.currentPage,
    size: paginationData.pageSize,
    state: stateSP.value,
    userName: searchData.userName || "",
    start: new Date(searchData.time[0]).getTime() || "", // 时间
    end: new Date(searchData.time[1]).getTime() || "" // 时间
  })
    .then((res: any) => {
      paginationData.total = res.data.total
      console.log(res, 123)
      tableData.value = res.data.list
      loading.value = false
      // ElMessage.success("success")
    })
    .catch(() => {
      tableData.value = []
    })
}
const handleSearch = () => {
  if (paginationData.currentPage === 1) {
    getTableData()
  }
  paginationData.currentPage = 1
}
const resetSearch = () => {
  searchFormRef.value?.resetFields()
  if (paginationData.currentPage === 1) {
    getTableData()
  }
  paginationData.currentPage = 1
}
// const handleRefresh = () => {
//   getTableData()
// }
//#endregion

// #region tabs切换
const activeName = ref("one")
const handleClick = (tab: TabsPaneContext) => {
  paginationData.currentPage = 1
  // console.log(tab.paneName)
  if (tab.paneName === "one") {
    stateSP.value = 0
  }
  if (tab.paneName == "two") {
    stateSP.value = 1
  }
  if (tab.paneName == "three") {
    stateSP.value = 2
  }
  getTableData()
}
const dialogVisible1 = ref<boolean>(false)
const handleOpenImgInfo = (imgUrl: any) => {
  dialogVisible1.value = true
  dialogImageUrl.value = imgUrl
}
const fileList1 = ref<UploadUserFile[]>([])
const dialogImageUrl = ref("")
const dialogVisible2 = ref(false)
const uploadFuc = async () => {
  if (currentUpdateId.value === undefined) {
    // 上传图片
    formData.state = 2
    const fileData = new FormData()
    fileList1.value.forEach((file: any) => {
      fileData.append("file", file.raw)
      console.log("file", file.raw)
    })
    if (fileList1.value.length != 0) {
      await ComplaintUpload(fileData).then((res: any) => {
        if (res.code == 200) {
          formData.image = res.data
            .map((item: any) => {
              return item.split("/image/")[1]
            })
            .join()
          console.log(formData.image, "拿到的图片")
          fileList1.value = []
        }
      })
    }
    await getwithdrawUpdate(formData).then((res: any) => {
      console.log(res)
      dialogVisible.value = false
      if (res.code == 200) {
        getTableData()
        ElMessage.success("打款失败")
      }
      getTableData()
    })
  } else {
    formData.state = 1
    // 上传图片
    const fileData = new FormData()
    fileList1.value.forEach((file: any) => {
      fileData.append("file", file.raw)
      console.log("file", file.raw)
    })
    if (fileList1.value.length != 0) {
      await ComplaintUpload(fileData).then((res: any) => {
        if (res.code == 200) {
          formData.image = res.data
            .map((item: any) => {
              return item.split("/image/")[1]
            })
            .join()
          console.log(formData.image, "拿到的图片")
          fileList1.value = []
        }
      })
    }
    await getwithdrawUpdate(formData).then((res: any) => {
      dialogVisible.value = false
      console.log(res, "打款成功")
      if (res.code == 200) {
        getTableData()
        ElMessage.success("打款成功")
      }
    })
  }
}
// 发布时图片改变
const handleChageImg1 = (file: any, resfileList: any) => {
  const size = ref(10)
  const fileSizeFlag = file.size / 1024 / 1024 < size.value
  if (!fileSizeFlag) {
    ElMessage.error(`请上传不大于${size.value}M的图片!`)
    fileList1.value = []
  } else {
    fileList1.value = resfileList
  }
}
const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible2.value = true
}
// #endregion

/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], getTableData, { immediate: true })
// ** 清除规则报错信息
const clearValidate = () => {
  formRef.value?.resetFields()
}
//时间
import { shortcuts } from "@/utils/dateSet"
const defaultTime1: [Date, Date] = [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 0)]
// 单条订单下载
const downLoad = async () => {
  await dakuanjiesuandown({
    start: new Date(searchData.time[0]).getTime() || "", // 时间
    end: new Date(searchData.time[1]).getTime() || "", // 时间
    userName: searchData.userName || "", // 分销账号
    state: 1 // 打款成功状态
  }).then((res: any) => {
    const blob = new Blob([res.data], {
      type: "application/xlsx;charset=utf-8"
    })
    const downloadElement = document.createElement("a")
    const href = window.URL.createObjectURL(blob)
    downloadElement.href = href
    downloadElement.download = "佣金结算列表.xlsx"
    document.body.appendChild(downloadElement)
    downloadElement.click()
    window.URL.revokeObjectURL(href)
    loading.value = false
    // console.log(blob, 88888888)
  })
}
</script>

<template>
  <div class="app-container">
    <!-- 搜索 -->
    <el-card shadow="never" class="search-wrapper">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="time" label="订单日期">
          <el-date-picker
            v-model="searchData.time"
            type="datetimerange"
            range-separator="到"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            :shortcuts="shortcuts"
            :default-time="defaultTime1"
          />
        </el-form-item>
        <el-form-item prop="userName" label="分销账号">
          <el-select v-model="searchData.userName" clearable filterable placeholder="请选择分销账号">
            <el-option
              v-for="item in userNameList"
              :key="item.user_id"
              :label="item.user_name"
              :value="item.user_name"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card v-loading="loading" shadow="never">
      <div class="toolbar-wrapper">
        <div>
          <el-tooltip content="下载">
            <el-button type="primary" :icon="Download" circle @click="downLoad" />
          </el-tooltip>
          <!-- <el-tooltip content="刷新表格">
            <el-button type="primary" :icon="RefreshRight" circle @click="handleRefresh" />
          </el-tooltip> -->
        </div>
      </div>
      <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
        <el-tab-pane label="审批提现" name="one" />
        <el-tab-pane label="打款成功" name="two" />
        <el-tab-pane label="打款失败" name="three" />
      </el-tabs>
      <div class="table-wrapper">
        <el-table :data="tableData">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column prop="id" label="订单ID" align="center" />
          <el-table-column prop="money" label="可结算金额" align="center" />
          <el-table-column prop="user_name" label="申请账号" align="center" />
          <el-table-column label="申请时间" align="center">
            <template #default="scope">
              {{ formatDateTime(scope.row.create_time) }}
            </template>
          </el-table-column>
          <el-table-column prop="bank" label="开户行" align="center" />
          <el-table-column prop="card_name" label="银行卡姓名" align="center" />
          <el-table-column prop="card_id" label="银行卡号" align="center" />
          <el-table-column prop="phone" label="手机号" align="center" />
          <el-table-column prop="note" label="备注" align="center" v-if="stateSP !== 0" />
          <el-table-column prop="image" label="图片" align="center" v-if="stateSP !== 0">
            <template #default="scope">
              <img
                :src="`http://fansitexitong.cn/image/${scope.row.image?.split(',')[0]}`"
                alt=""
                style="cursor: pointer"
                v-if="scope.row.image"
                width="80"
                height="80"
                @click="handleOpenImgInfo(scope.row.image)"
              />
            </template>
          </el-table-column>
          <el-table-column label="提现状态" align="center">
            <template #default="scope">
              <el-text class="mx-1" v-if="scope.row.state == 0" type="primary">提现中</el-text>
              <el-text class="mx-1" v-if="scope.row.state == 1" type="success">提现成功</el-text>
              <el-text class="mx-1" v-if="scope.row.state == 2" type="danger">提现失败</el-text>
            </template>
          </el-table-column>
          <el-table-column
            fixed="right"
            label="操作"
            width="150"
            align="center"
            style="display: flex"
            v-if="stateSP == 0"
          >
            <template #default="scope">
              <el-text style="margin-right: 0.625rem" class="mx-1" type="success" @click="handleUpdate(scope.row)"
                >打款成功</el-text
              >
              <el-text class="mx-1" type="danger" @click="handleUpdate1(scope.row)">打款失败</el-text>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页器 -->
      <div class="pager-wrapper">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
      <!-- 新增/修改 -->
      <el-dialog
        v-model="dialogVisible"
        :title="currentUpdateId === undefined ? '打款失败' : '打款成功'"
        @close="resetForm"
        width="60%"
      >
        <el-form ref="formRef" :model="formData" :rules="formRules" label-width="6.25rem" label-position="left">
          <el-form-item prop="note" label="备注">
            <el-input v-model="formData.note" placeholder="请输入" />
          </el-form-item>
          <!-- 反馈图片 -->
          <el-form-item prop="image" label="上传图片">
            <el-upload
              :multiple="true"
              :auto-upload="false"
              :file-list="fileList1"
              :show-file-list="true"
              list-type="picture-card"
              accept="image/*"
              :on-change="handleChageImg1"
              :on-preview="handlePictureCardPreview"
            >
              <el-icon><Plus /></el-icon>
            </el-upload>

            <el-dialog v-model="dialogVisible2">
              <img w-full :src="dialogImageUrl" alt="Preview Image" />
            </el-dialog>
          </el-form-item>
        </el-form>

        <template #footer>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleCreate">确定</el-button>
        </template>
      </el-dialog>
      <!--       v-for="(item, index) in ruleFormXQ.data.Kimage.split(',')" -->
      <!--     v-for="(item, index) in formWorkOrder.data.kimage.slice(0, -1).split(',')" -->
      <!--       v-for="(item, index) in srcList" -->
      <!-- <el-form-item prop="image" label="纠纷单图片" v-if="ruleFormXQ.data.Kimage !== ''">
        <el-image
          class="JFimage"
          v-for="(item, index) in ruleFormXQ.data.Kimage.slice(0, -1).split(',')"
          :preview-src-list="[item]"
          :key="index"
          :src="item"
          :zoom-rate="1.2"
          fit="cover"
        />
      </el-form-item> -->
    </el-card>
  </div>
</template>

<style lang="scss" scoped>
.search-wrapper {
  margin-bottom: 1.25rem;
  :deep(.el-card__body) {
    padding-bottom: 0.125rem;
  }
}

.toolbar-wrapper {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 1.25rem;
}

.table-wrapper {
  margin-bottom: 1.25rem;
}

.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}
.avatar-uploader .avatar {
  width: 11.125rem;
  height: 11.125rem;
  display: block;
}
.block {
  padding: 1.875rem 0;
  text-align: center;
  box-sizing: border-box;
  vertical-align: top;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 0.0625rem dashed var(--el-border-color);
  border-radius: 0.375rem;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 1.75rem;
  color: #8c939d;
  width: 11.125rem;
  height: 11.125rem;
  text-align: center;
}
</style>
